07. Abstract Classes
Abstract Classes
ND079 C1 L3 A06 Abstract Class
An abstract class has the following key characteristics:
- It defines the behavior for each of the subclasses, but we cannot directly instantiate the abstract class itself.
- It allows us to create abstract methods.
- An abstract method is a method that does not contain an implementation body. Instead, it simply provides a header for the method.
- Subclasses that extend an abstract class are required to override all abstract methods and provide a specific implementation.
Example: Abstract Vehicle
Class
Here's the example we looked at in the video. To ensure that we will not be able to directly instantiate Vehicle
objects from this class, we define it using the abstract
keyword:
public abstract class Vehicle {
protected String start;
protected String stop;
protected String direction;
public Vehicle(String start, String stop,
String direction) {
this.start = start;
this.stop = stop;
this.direction = direction;
}
public abstract void speed();
}
Next, we use the Extends
keyword to have our Car
class extend the Vehicle
class:
public class Car extends Vehicle {
public Car() {
super("Car start", "Car stop", "Car direction");
}
@Override
public void speed() {
System.out.println("55");
}
}
Thus, although we cannot directly instantiate objects from the abstract Vehicle
class, we can instantiate objects from the Car
class, and they will have all the behavior of a Vehicle
.